package servlet;

import entity.Emp;
import service.EmpServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

/**
 * @author lvtian
 * @date 2022/12/20 15:20
 */
@WebServlet("/Emp.do")
public class EmpServlet extends BaseServlet{
    private EmpServiceImpl service = new EmpServiceImpl();
    //查看所有员工
    public void selectAll(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        List<Emp> emps = service.selectEmp();
        req.setAttribute("emps",emps);
        req.getRequestDispatcher("/allEmp.jsp").forward(req,resp);
    }

    //添加
    public void add(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        String name = req.getParameter("name");
        Integer age = Integer.parseInt(req.getParameter("age"));
        String gender = req.getParameter("gender");
        System.out.println(gender);
        int i = service.addEmp(new Emp(0, name, age, gender));
        if(i>0){
            req.getRequestDispatcher("/Emp.do?m=selectAll").forward(req, resp);
        }

    }
    //修改
    public void update(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        Integer id = Integer.parseInt(req.getParameter("id"));
        String name = req.getParameter("name");
        Integer age = Integer.parseInt(req.getParameter("age"));
        String gender = req.getParameter("gender");

        int i = service.updateEmp(new Emp(id, name, age, gender));
        if(i>0){
            req.getRequestDispatcher("/Emp.do?m=selectAll").forward(req, resp);
        }
    }
    //删除
    public void delete(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        Integer id = Integer.parseInt(req.getParameter("id"));
        int i = service.deleteEmp(id);
        req.getRequestDispatcher("/Emp.do?m=selectAll").forward(req,resp);
    }
    //通过id查找
    public void selectById(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        Integer id = Integer.parseInt(req.getParameter("id"));
        List<Emp> emps = service.selectEmpById(id);
        Emp e = null;
        if(emps!=null && emps.size()>0){
            e=emps.get(0);
        }
        req.setAttribute("e", e);
        req.getRequestDispatcher("/updateEmp.jsp").forward(req,resp);

    }
//通过名字查找
public void check(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    String name = req.getParameter("name");
    List<Emp> emps = service.selectEmpByName(name);
    if( emps !=null && emps.size()>0){
        resp.getWriter().print(1);
    }else {
        resp.getWriter().print(0);
    }
}
}
